package br.com.egg.finances.view.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.egg.finances.view.EntityBean;

public class SessionTimeoutFilter implements Filter {

	private final static String TIMEOUT_PAGE = "index.jsf";
	private final static String SIGNIN_PAGE = "cadUsuario.jsf";
	private final static String INITIAL_PAGE = "viewExtrato.jsf";
	
	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		if (areHttpServlet(request, response)) {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			HttpServletResponse httpServletResponse = (HttpServletResponse) response;
			
			if (isSessionControlRequiredForThisResource(httpServletRequest)) {
				if (isSessionInvalid(httpServletRequest)) {
					String timeoutUrl = httpServletRequest.getContextPath() + "/" + TIMEOUT_PAGE;
					httpServletResponse.sendRedirect(timeoutUrl);
					return;
				}
			} else if (isSessionValid(httpServletRequest)) {
				String timeoutUrl = httpServletRequest.getContextPath() + "/" + INITIAL_PAGE;
				httpServletResponse.sendRedirect(timeoutUrl);
			}
		}
		filterChain.doFilter(request, response);
	}

	private boolean areHttpServlet(ServletRequest request, ServletResponse response) {
		return request instanceof HttpServletRequest && response instanceof HttpServletResponse;
	}

	private boolean isSessionControlRequiredForThisResource(HttpServletRequest httpServletRequest) {
		String requestPath = httpServletRequest.getRequestURI();
		boolean controlRequired = !(requestPath.contains(TIMEOUT_PAGE) || requestPath.contains(SIGNIN_PAGE));
		return controlRequired;
	}
	
	private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {
		HttpSession session = httpServletRequest.getSession();
		boolean sessionInvalid = session.getAttribute(EntityBean.ATTRIBUTE_USUARIO) == null;
		return sessionInvalid;
	}
	
	private boolean isSessionValid(HttpServletRequest httpServletRequest) {
		HttpSession session = httpServletRequest.getSession();
		boolean sessionInvalid = session.getAttribute(EntityBean.ATTRIBUTE_USUARIO) != null;
		return sessionInvalid;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {}

}
